import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    keyList: 'all'
  },
  getters: {
    undoneLength(state) {
      return state.list.filter(v => !v.done).length
    },
    list(state) {
      if (state.keyList === 'undone') {
        return state.list.filter(v => !v.done)
      }
      if (state.keyList === 'done') {
        return state.list.filter(v => v.done)
      }
      return state.list
    }
  },
  mutations: {
    setList(state, payload) {
      state.list = payload.list
    },
    addItem(state, payload) {
      state.list.push({
        id: Date.now(),
        info: payload.info,
        done: false
      })
    },
    deleteItem(state, payload) {
      const index = state.list.findIndex(v => v.id === payload.id)
      state.list.splice(index, 1)
    },
    changeItemStatus(state, payload) {
      const item = state.list.find(v => v.id === payload.id)
      item.done = !item.done
    },
    cleanDone(state) {
      state.list = state.list.filter(v => !v.done)
    },
    changeList(state, payload) {
      state.keyList = payload.key
    }
  },
  actions: {
    async getList(context) {
      const res = await axios.get('/list.json')
      context.commit('setList', { list: res.data })
    }
  },
  modules: {}
})
